package _interview150;

/**
 * 123. 买卖股票的最佳时机 III
 */
public class No123 {
    private int[] prices;
    private int[][][] cache;

    public int maxProfit1(int[] prices) {
        this.prices = prices;
        int n = prices.length;
        cache = new int[n][3][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 2; k++) {
                    cache[i][j][k] = -1;
                }
            }
        }
        return dfs(n - 1, 2, 0);
    }

    private int dfs(int i, int j, int hold) {
        if (j < 0) return Integer.MIN_VALUE / 2;
        else if (i < 0) return hold == 0 ? 0 : Integer.MIN_VALUE / 2;
        else if (cache[i][j][hold] != -1) return cache[i][j][hold];
        else if (hold == 1) return cache[i][j][hold] = Math.max(dfs(i - 1, j, 1), dfs(i - 1, j, 0) - prices[i]);
        else return cache[i][j][hold] = Math.max(dfs(i - 1, j, 0), dfs(i - 1, j - 1, 1) + prices[i]);
    }

    public int maxProfit2(int[] prices) {
        int n = prices.length;
        int[][][] f = new int[n + 1][4][2];
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                for (int k = 0; k < 2; k++) {
                    if (j == 0) f[i][j][k] = Integer.MIN_VALUE / 2;
                    else if (i == 0) f[i][j][k] = k == 0 ? 0 : Integer.MIN_VALUE / 2;
                }
            }
        }
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < 3; j++) {
                f[i + 1][j + 1][1] = Math.max(f[i][j + 1][1], f[i][j + 1][0] - prices[i]);
                f[i + 1][j + 1][0] = Math.max(f[i][j + 1][0], f[i][j][1] + prices[i]);
            }
        }
        return f[n][3][0];
    }
}
